var pressEnter = function(event){ // corrige o bug do enter
	if(event.keyCode == 13 && $(this).attr('tagName')=='INPUT') $(this).data('myform').submit();
}
$(document).ready(function(){
	validateForm();
});

function validateForm(){
	var forms = $('form.validate');

	if(forms.length>0){
		
		$.validator.addMethod('emailMultiplo', function(emails, element) {
			var size,i,arrayEmail,filter,flag; 			
			var arrEmailsValidos = new Array();

			filter		= /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
			emails		= emails.replace(/ /gi,'').replace(/\,/gi,';');
			arrayEmail	= emails.split(';')
			size		= arrayEmail.length;
			
			flag = true;
			for(i=0; i<size; i++){
				if(!filter.test(arrayEmail[i]) || arrayEmail[i].length == 0){
					if (arrayEmail[i].length == 0){
						continue;
					}else{
						flag = false;
						break;
					}
				}else{
					arrEmailsValidos.push(arrayEmail[i]);
				}
			}

			if (arrEmailsValidos.length == 0)
				flag = false;
			

			return (this.optional(element) || flag);
		},'Existem e-mails preenchidos incorretamente.');

		$.validator.addMethod('cep', function(cep, element) {
			return (this.optional(element) || cep.replace(/[^0-9]/gi,'').length==8);
		},'Informe um CEP v&aacute;lido.');
		
		$.validator.addMethod('telefone', function(telefone, element) {
			var telefone = telefone.replace(/[^0-9]/gi,'');
			return (this.optional(element) || (telefone.length==10 && parseInt(telefone.substring(0,2)) > 10 && parseInt(telefone.substring(2,3))>1));
		},'Informe um telefone v&aacute;lido.');
		
		$.validator.addMethod('telefoneFixo', function(telefone, element) {
			var telefone = telefone.replace(/[^0-9]/gi,'');
			var numero = parseInt(telefone.substring(2,3));
			return (this.optional(element) || (telefone.length==10 && parseInt(telefone.substring(0,2)) > 10 && numero>1 && numero<6));
		},'Informe um telefone fixo v&aacute;lido.');
		
		$.validator.addMethod('celular', function(celular, element) {
			var celular = celular.replace(/[^0-9]/gi,'');
			return (this.optional(element) || (celular.length==10 && parseInt(celular.substring(0,2)) > 10 && parseInt(celular.substring(2,3))>5));
		},'Informe um telefone celular v&aacute;lido.');
		
		$.validator.addMethod('cpf', function(cpf, element) {
			cpf = cpf.replace(/[^0-9]/gi,'');
			while(cpf.length < 11) cpf = '0'+ cpf;
			var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/;
			var a = [];
			var b = new Number;
			var c = 11;
			for (i=0; i<11; i++){
				a[i] = cpf.charAt(i);
				if (i < 9) b += (a[i] * --c);
			}
			if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
			b = 0;
			c = 11;
			for (y=0; y<10; y++) b += (a[y] * c--);
			if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
			
			return (this.optional(element) || ((cpf.charAt(9) == a[9]) && (cpf.charAt(10) == a[10]) && !cpf.match(expReg)));
		}, 'Informe um CPF v&aacute;lido.');
		
		$.validator.addMethod('cnpj', function(cnpj, element) {
			var cnpj = cnpj.replace(/[^0-9]/gi,'');
			var valida = new Array(6,5,4,3,2,9,8,7,6,5,4,3,2);
			var dig1 = new Number;
			var dig2 = new Number;			
			var digito = new Number(eval(cnpj.charAt(12)+cnpj.charAt(13)));
			
			for(i = 0; i<valida.length; i++){
				dig1 += (i>0? (cnpj.charAt(i-1)*valida[i]):0);  
				dig2 += cnpj.charAt(i)*valida[i];       
			}
			
			dig1 = (((dig1%11)<2)? 0:(11-(dig1%11)));
			dig2 = (((dig2%11)<2)? 0:(11-(dig2%11)));
			
			return (this.optional(element) || ((dig1*10)+dig2) == digito);
		}, 'Informe um CNPJ v&aacute;lido.');
		
		$.validator.addMethod('date', function(value, element) {
			var check = false;
			if(/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(value)){
				var adata = value.split('/');
				var gg = parseInt(adata[0],10);
				var mm = parseInt(adata[1],10);
				var aaaa = parseInt(adata[2],10);
				var xdata = new Date(aaaa,mm-1,gg);
				check = ( xdata.getFullYear() == aaaa ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == gg );
			}
			return this.optional(element) || check;
		}, "Informe uma data v&aacute;lida.");
		
		$.validator.addMethod("maxWords", function(value, element, params) { 
	   		var match = value.match(/\b\w+\b/gi);
			if(!match) return false;
			return this.optional(element) || value.match(/\b\w+\b/gi).length < params; 
		}, $.validator.format("Informe&nbsp;{0} palavras ou menos.")); 
		 
		$.validator.addMethod("minWords", function(value, element, params) { 
			var match = value.match(/\b\w+\b/gi);
			if(!match) return false;
			return this.optional(element) || value.match(/\b\w+\b/gi).length >= params; 
		}, $.validator.format("Informe&nbsp;{0} palavras ou mais.")); 
		 
		$.validator.addMethod("rangeWords", function(value, element, params) {
			var match1 = value.match(/\b\w+\b/g);
			var match2 = value.match(/bw+b/g);
			if(!match1 || !match2) return false;
			return this.optional(element) || match1.length >= params[0] && match2.length < params[1]; 
		}, $.validator.format("Informe&nbsp;entre {0} e {1} palavras."));
		
		var inputCleanup = function(input){
			var input = $(input);
			var defaultValue = input.attr('defaultValue');
			if(defaultValue){
				if(input.val().toLowerCase()==defaultValue.toLowerCase()){
					input.val('');
				}
			}
		}
		
	}
	
	forms.each(function(){
		
		var form			= $(this);
		var inputs			= $(':input[title]',this);
		var evalRules		= '';
		var evalMessages	= '';
		var evalGroups		= '';
		
		inputs.each(function(){
			
			try{eval(("validate={"+$(this).attr('title')+"}").replace(/\;/gi,',').replace(/\,\,/gi,',').replace(/\,\}/gi,'}'));}catch(e){return}
			
			var input = $(this)
				.removeAttr('title')
				.data('validate',validate)
				.data('myform',form)
				.bind('keypress',pressEnter);

			if(validate.title) input.attr('title',validate.title);
			
			if(validate.cleanup){
				var defaultValue = input.attr('defaultValue');// adiciona a classe 'default-value' nos campos
				if(defaultValue){
					if(input.val().toLowerCase()==defaultValue.toLowerCase()&&!input.hasClass('default-value')){
						input.addClass('default-value');
					}
				}
				input.bind('focus',function(){//remove o valor default dos campos quando focado
					inputCleanup(this);
				}).bind('blur',function(){// adiciona o valor default quando o cursor sai do campo e o valor for vazio
					var input = $(this);
					var defaultValue = input.attr('defaultValue');
					if(input.val().replace(/ /gi,'')==''&&defaultValue){
						input.val(defaultValue).addClass('default-value');
					}
				}).bind('keydown',function(){// remove a classe 'default-value' dos campos
					var input = $(this);
					var defaultValue = input.attr('defaultValue');
					if(defaultValue){
						if(input.val().toLowerCase()!=defaultValue.toLowerCase()){
							input.removeClass('default-value');
						}else if(!input.hasClass('default-value')){
							input.addClass('default-value');
						}
					}
				});
			}

			if(validate.mask){// cria a m&aacute;scara conforme o padrão criado. ex: ###.###.###-##
				if(!validate.mask_char) input.data('validate').mask_char = '#';
				input.bind('keypress',function(event){
					var input = $(this);
					if(event.charCode==undefined) event.charCode = event.keyCode;
					if(event.charCode>0){
						var char = String.fromCharCode(event.charCode);
						var mask = input.data('validate').mask_char;
						var text = input.data('validate').mask.substring(input.val().length).substring(0,1);
						if(text != mask && text!=char){
							input.val(input.val()+text);
						}
					}
				}).bind('keyup',function(){
					var input = $(this);
					if(input.val().substring(0,1)!=input.data('validate').mask.substring(0,1)&&input.val().length>0&&input.data('validate').mask_char!=input.data('validate').mask.substring(0,1)){
						input.val(input.data('validate').mask.substring(0,1) + input.val());
					}
				});
			}

			if(parseInt(validate.maxlength)>0 && (parseInt(input.attr('maxlength'))<1 || parseInt(input.attr('maxlength')).toString()=='NaN')){
				input.attr('maxlength',validate.maxlength).data('maxlength',validate.maxlength);
			}else if(parseInt(input.attr('maxlength'))>0 && parseInt(input.attr('maxlength')).toString()!='NaN'){
				input.data('maxlength',input.attr('maxlength'));
			}
			
			if(input.attr('tagName')=='TEXTAREA'){
				input.bind('keypress',function(event){
					var input = $(this);						
					if(event.charCode==undefined) event.charCode = event.keyCode;
					if(event.charCode>0){							
						var maxlength = parseInt(input.data('maxlength'));
						if(input.val().length >= maxlength && maxlength>0){								
							return false;
						}
					}
				});
			}
			
			if(validate.autotab){ // autotab: pula automaticamente para o próximo campo, ou campo informado ao chegar no tamanho m&aacute;ximo.
				if(typeof(validate.autotab)=='boolean'){
					$(':input[type!="hidden"]',form).attr('index',function(index){return index}).each(function(index){
						$(this).data('nextInput',$('[index='+(parseInt(index)+1)+']',form))
					}).removeAttr('index');
				}else{
					input.data('nextInput',$(validate.autotab));
				}
				if(input.data('nextInput').length>0){
					input.bind('keypress',function(event){
						if(event.charCode==undefined) event.charCode = event.keyCode;
						$(this).data('autotab',(event.charCode>0));
					}).bind('keyup',function(event){
						var input = $(this);
						var maxlength = parseInt(input.data('maxlength'));
						if(input.data('autotab') && input.val().length >= maxlength && maxlength>0){
							input.data('nextInput').focus();
						}
					});
				}
			}
			
			evalRules 		+= (evalRules!=''?',':'') + input.attr('name') + ':{';
			evalMessages 	+= (evalMessages!=''?',':'') + input.attr('name') + ':{';

			$.each(validate,function(prop,value){
				var prop = prop.toString();
				var value = (typeof(value)=='string' ? "\\'"+value+"\\'" : value);
				eval(	"if(typeof($.validator.methods."+prop+")!='undefined'){"+
						"	evalRules += '"+prop+":"+value+","+((validate.cleanup&&prop=='required') ? "depends:inputCleanup," : "")+"';"+
						"	if(validate.msg_"+prop+"){"+
						"		evalMessages += '"+prop+":\"'+validate.msg_"+prop+"+'\",';"+
						"	}else if(validate.msg){"+
						"		evalMessages += '"+prop+":\"'+validate.msg+'\",';"+
						"	}"+((prop=='required')?"else{evalMessages += 'required:\"Preenchimento obrigat&oacute;rio.\",'}":"")+
						"}");
			});
			
			evalRules += '}';
			evalRules = evalRules.replace(/\,\}/gi,'}');
			
			evalMessages += '}';
			evalMessages = evalMessages.replace(/\,\}/gi,'}');
			
			if(validate.group){					
				evalGroups += (evalGroups!=''?',':'') + input.attr('name') + ':"' + input.attr('name')+' '+validate.group+'"';
				if(!validate.localError){
					$.each(validate.group.split(' '), function(i,name){
						if(name.length>0) $(':input[name="'+name+'"]',form).data('localError',input).data('localErrorGroup',true);
					});
				}
			}

			if(validate.localError) input.data('localError', $(validate.localError));

		});
		
		if(evalRules!=''){
			
			try{
			eval('evalRules={'+evalRules+'}');
			eval('evalMessages={'+evalMessages+'}');
			eval('evalGroups={'+evalGroups+'}');
			}catch(e){return}

			if(form.attr('onsubmit')) form.data('submitHandler',form.attr('onsubmit')).removeAttr('onsubmit');
			
			form.validate({
				ignore: ".ignore-validate, .hide, .hide input, .hide select, .hide textarea",
				errorClass:'input-error',
				errorElement:'div',				
				wrapper:'div',
				rules:evalRules,
				messages:evalMessages,
				groups:evalGroups,
				errorPlacement:function(error,input){
					var localError = input.data('localError');
					clearTimeout(window.closeAllErrors);
					error.addClass('input-error-global').attr('title','Clique para fechar.').click(function(){
						error.fadeOut(300);
					});					
					if(!localError){
						input.after(error);						
					}else{			
						switch(input.data('validate').localErrorMethod){							
							case 'before': localError.before(error); break;
							case 'after': localError.after(error); break;
							case 'prepend': localError.prepend(error); break;
							default: localError.append(error);
						}						
					}
					error.css('display','inline-block');
					if(error.css('position')=='absolute'){
						if(localError && input.data('validate').localErrorGroup){
							input = localError;
						}
						var left = parseInt(error.parent().css('padding-left').replace('px'));
						var top	= parseInt(error.parent().css('padding-top').replace('px'));
						left = (isNaN(left)? 0 : left);
						top = (isNaN(top)? 0 : top);
						error.parent().css('position','relative');
						error.append('<samp></samp>').css('top',function(){
							return (((input.position().top-top)-2)-$(this).height())+'px';
						}).css('left',function(){
							return (input.position().left-left)+'px';
						});
					}
					error.prepend('<span class="error-icon"></span>');
					error.fadeIn(300);
					window.closeAllErrors = setTimeout("$('.input-error-global').fadeOut(300)",20000);
				},
				submitHandler:function(form){
					try{if($(form).data('submitHandler')){eval($(form).data('submitHandler'));}}catch(e){}
					$('.default-value',form).val('');
					$(form).unbind('submit').submit();
				}
			});
		}
	});
}